import time
import os
from collections import OrderedDict
from django.template import loader
from django.conf import settings

from .models import ContentCategory
from goods.utils import get_categories


def generate_static_index_html():
    """生成静态的主页html文件"""
    print('%s: generate_static_index_html' % time.ctime())
    # 1.获取页面中需要的数据
    # 获取商品分类信息
    categories = get_categories()
    # 获取广告数据
    # contents = {}
    contents = OrderedDict()
    # 查询广告分类数据
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        # 以分类的类别键名为键，对应的广告内容为值，保存在字典中
        # 按照状态是展示，根据内部排序号排序查询数据
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
    # 构造数据
    context = {
        'categories': categories,
        'contents': contents
    }
    # 2.获取模板，loader.get_template会自动到模板目录中查找
    template = loader.get_template('index.html')
    # 3.渲染模板，获取到html数据
    html_text = template.render(context)
    # 4.把渲染后的数据写到html中
    # 获取html文件路径
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
    # 把html数据写入到文件中
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)
